
#include "CondB.h"
#include "base/core/utility.h"
#include "Common/TableDataEx/DuplicateCfg.h"


CondB::CondB() :m_pDuplicate(nullptr), m_pVecCond(nullptr), m_result(-1), m_finish(false), m_limitSec(0)
{
	m_setType.clear();
	m_openPlayerDie = 0;
	m_playerDie = false;
}

CondB::~CondB()
{

}

bool CondB::init(IDuplicate *pDuplicate, const VEC_INT32 *pCond, const string &strSubCond)
{
	if (nullptr == pDuplicate || nullptr == pCond)
	{
		return false;
	}
	//2，限制时间
	int32_t isize = pCond->size();
	if (isize < 2)
	{
		LogErrFmtPrint("[logic] CondB::init....isize < 2, dupid:%u, sceneid:%u , isize:%d ", pDuplicate->GetDuplicateID(), pDuplicate->GetSceneID(), isize);
		return false;
	}
	else if (isize >= 3)
	{
		m_openPlayerDie = (int8_t)pCond->at(2);
	}
	//解析怪物序列
	CommonApi::SplitStrToSetInt(strSubCond, ",", &m_setType);
	//移除类型为0的
	SET_INT32::iterator iterdel = m_setType.find(0);
	if (iterdel != m_setType.end())
	{
		m_setType.erase(iterdel);
	}

	m_pVecCond = pCond;
	m_pDuplicate = pDuplicate;
	m_limitSec = m_pVecCond->at(1);
	

	return true;
}

void CondB::uninit()
{
	m_pDuplicate = nullptr;
	m_pVecCond = nullptr;
	m_finish = false;
	m_result = -1;
	m_limitSec = 0;
	m_setType.clear();
	m_openPlayerDie = 0;
	m_playerDie = false;
}

bool CondB::finishCond()
{
	return m_finish;
}

int32_t CondB::limitSec()
{
	return m_limitSec;
}

int32_t CondB::result()
{
	return m_result;
}

void CondB::onMonDie(uint32_t monsId, uint32_t num, int32_t leftNum)
{
	_UNUSE(monsId);
	_UNUSE(num);
	notifyMonsNum();
}

void CondB::onCreatrueDie(uint64_t cid, int8_t creatureKind)
{
	_UNUSE(cid);
	if (CREATURE_PLAYER == creatureKind)
	{
		m_playerDie = true;
	}
}

void CondB::notifyMonsNum()
{
	if (nullptr == m_pDuplicate)
	{
		return;
	}
	Duplicate_MonsNumRsp rsp;
	rsp.set_num(m_pDuplicate->GetMonsterNum(m_setType));
	m_pDuplicate->BroadCastData(EMODULE_ID_DUPLICATE, LOGIC_TO_CLIENT_DUPLICATE_MONSTER_NUM, &rsp);
}

void CondB::condUpdate()
{
	if (m_finish)
	{
		return;
	}
	m_result = checkCond();
	if (RET_SUCCESS == m_result || RET_FAIL == m_result)
	{
		m_finish = true;
	}
}

int32_t CondB::checkCond()
{
	if (nullptr == m_pVecCond || nullptr == m_pDuplicate)
	{
		return -1;
	}
	int32_t ret = -1;
	uint64_t curTime = g_GetGlobalServerTime()->UnixSec();
	int32_t interSec = (int32_t)(curTime - m_pDuplicate->StartBrushTime());

	/*
	1，指定时间内消灭指定怪物序列，才能通关；超时失败
	2，指定时间内消灭所有怪物，才能通关；超时失败
	3，消灭所有怪物，才能通关；塔被怪物消灭失败
	4，达到指定时间点，怪物传送的数量小于目标值；怪物传送的数量达到目标值，或有BOSS进行传送，失败

	1，限制时间，怪物1的ID，怪物2的ID，……
	2，限制时间
	3，塔的ID
	4，限制时间，传送区域ID，目标值，BOSS1的ID，BOSS2的ID，……
	*/



	if (0 == m_pDuplicate->GetMonsterNum(m_setType)) //怪物全部死亡
	{
		ret = RET_SUCCESS;
	}
	else if (interSec >= m_limitSec)
	{
		ret = RET_FAIL;
	}
	else if (m_openPlayerDie && m_playerDie) //如果开启玩家死亡 副本失败， 并且玩家死亡了
	{
		ret = RET_FAIL;
	}

	return ret;
}